<template>
    <div class="app-container">
      <div class="search-bar">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="脚本名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
            <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
  
      <el-card shadow="never">
        <div class="mb-[10px]" v-if="isAdmin">
          <el-button type="success" icon="plus" @click="handleAddClick">导入脚本</el-button>
          <el-button type="danger" :disabled="ids.length === 0" icon="delete" @click="handleBatchDelete">删除</el-button>
        </div>
  
        <el-table
            @cell-click="handleRowClick"
            v-loading="loading"
            :data="tableData"
            border
            @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" fixed="left" align="center" v-if="isAdmin" />
          <el-table-column label="脚本名称" prop="name" width="200" />
          <el-table-column label="文件大小（字节）" prop="size" width="200" />
          <el-table-column label="版本号" prop="version" max-width="250">
            <template #default="scope">
                {{ scope.row.version || '--'}}
            </template>
          </el-table-column>
          <el-table-column label="脚本描述" prop="description" min-width="200">
            <template #default="scope">
                {{ scope.row.description || '--'}}
            </template>
          </el-table-column>
          <el-table-column label="更新时间" prop="updatedAt" width="200">
            <template #default="scope">
                {{ scope.row.updatedAt? formatDate(scope.row.updatedAt) : '--'}}
            </template>
          </el-table-column>
          <el-table-column v-if="isAdmin" label="创建人账号" prop="owner" width="150"/>
          <el-table-column label="创建时间" prop="createdAt" width="200">
            <template #default="scope">
                {{ scope.row.createdAt ? formatDate(scope.row.createdAt) : '--'}}
            </template>
          </el-table-column>
          <el-table-column label="访问模式" prop="accessMode" width="150" v-if="isAdmin">
            <template #default="scope">
                <el-tag type="success" v-if="scope.row.accessMode === 'public'">公开</el-tag>
                <el-tag type="primary" v-if="scope.row.accessMode === 'whitelist'">白名单</el-tag>
                <el-tag type="warning" v-if="scope.row.accessMode === 'blacklist'">黑名单</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="白名单或黑名单" prop="accessList" width="200" v-if="isAdmin">
            <template #default="scope">
                {{ scope.row.accessList.length ? scope.row.accessList.join(',') : '--'}}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" :width="isAdmin ? 180 : 100">
            <template #default="scope">
                <div v-if="isAdmin">
                    <el-button type="primary" link size="mini" @click="downloadScript(scope.row)">下载脚本</el-button>
                    <el-button type="primary" link size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="danger" link size="mini" @click="handleDeleteOne(scope.row)">删除</el-button>
                </div>
                <div v-else>
                    <el-button type="primary" link size="mini" @click="downloadScript(scope.row)">下载脚本</el-button>
                </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            v-model:current-page="paging.page"
            v-model:page-size="paging.size"
            :page-sizes="[10, 20, 30, 50, 100]"
            :size="paging.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="paging.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <AddEditForm v-if="isAdmin" ref="addEditFormRef" @refresh="getList" />
    </div>
  </template>
  
  <script setup>
  import { useRouter } from 'vue-router'
  import { formatDate } from "@/utils";
  import { downloadFile } from "@/utils/download";
  import { getListApi, getCountApi, deleteByIdApi, deleteByIdsApi, getDownloadApi } from "@/api/scriptManage/index.api";
  import useToggle from "@/hooks/useToggle";
  import AddEditForm from "./addEditForm.vue";
  import { useUserStore } from "@/store";
  const { userInfo } = useUserStore();
  

  const isAdmin = computed(() => {
      return userInfo.role === 'admin'
  })

  const router = useRouter()

  const paging = ref({
    size: 10,
    page: 1,
    total: 0,
  })
  
  const handleSizeChange = (e) => {
    paging.value.size = e
    getList()
  }
  const handleCurrentChange = (e) => {
    paging.value.page = e
    getList()
  }
  
  const ids = ref([])
  const loading = ref(false)
  const tableData = ref([])
  const queryParams = ref({
    name: ''
  })
  const handleQuery = () => {
    getList()
  }
  const handleResetQuery = () => {
    queryParams.value.name = ''
    paging.value.page = 1
    paging.value.size = 10
    getList()
  }
  const handleSelectionChange = (e) => {
    ids.value = e.map(item => item.id)
  }

  const addEditFormRef = ref(null)
  const handleAddClick = () => {
    addEditFormRef.value.init()
  }
  const handleDelete = () => {}

  const getList = () => {
    loading.value = true

    const params = { 
        limit: paging.value.size,
        offset: (paging.value.page - 1) * paging.value.size
    }
    if (queryParams.value.name) {
      params.name = queryParams.value.name
    }

    getListApi(params).then((res) => {
        tableData.value = res
    }).finally(() => {
        loading.value = false
    })

    getCountApi(params).then((res) => {
        paging.value.total = res
    })
  }

  const handleBatchDelete = () => {
    if (ids.value.length === 0) return ElMessage.error('请选择要删除的脚本')
    ElMessageBox.confirm(`是否确认删除选中的${ids.value.length}个脚本?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
        loading.value = true
        deleteByIdsApi(ids.value).then((res) => {
            getList()
        }).finally(() => {
            loading.value = false
        })
    })
  }

  const handleDeleteOne = (row) => {
    ElMessageBox.confirm('是否确认删除该脚本?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
        loading.value = true
        deleteByIdApi(row.id).then((res) => {
            console.log(res)
            loading.value = false
            ElMessage({
                message: '删除成功',
                type: 'success',
            })
            getList()
        })
    })
  }

  const handleEdit = (row) => {
    addEditFormRef.value.init(row)
  }

  const downloadScript = (row) => {
    const loadingDownload = ElLoading.service({
      lock: true,
      text: '正在下载中，请稍后...',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    getDownloadApi(row.id).then((res) => {
        downloadFile(res, row.name)
    }).finally(() => {
        loadingDownload.close()
    })
  }

  const handleRowClick = (row, column) => {
    if(!column.property) return

    router.push({
        path: `/scriptManage/scriptConfigList`,
        query: {
            name: row.name,
            id: row.id
        }
    })
  }

  onMounted(() => {
    getList()
  })
  </script>
  
  <style scoped lang="scss">
  .pagination{
    display: flex;
    justify-content: flex-end;
    margin-top: 15px;
  }
  </style>
